import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;

public class Client {

	private Socket socket = null;

	private String strIP = "127.0.0.1";

	private int iPort = 8189;

	private Client() {
		//connect server.
		try {
			socket = new Socket(strIP, iPort);
			System.out.println("connect server success.");
		} catch (Exception e) {
			System.out.println("******connect server error.");
			e.printStackTrace();
			if (socket != null)
				try {
					socket.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
		} finally {
		}

		System.out.println("ready to send url");

		// send URL
		try {
			DataOutputStream outStream = new DataOutputStream(socket
					.getOutputStream());
			String strURL = "http://www.youtube.com/watch?v=9xJeQfMLzO0&feature=related";
			outStream.writeUTF(strURL);
			outStream.flush();
			System.out.println("send url success");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("*****send url error");
		}

		System.out.println("ready to send file");
		//get message
		try {
			DataInputStream inStream = new DataInputStream(
					new BufferedInputStream(socket.getInputStream()));

			try {
				String savePath = System.getProperty("user.dir") + "/";
				int bufferSize = 8096;
				byte[] buf = new byte[bufferSize];
				int passedlen = 0;
				savePath += inStream.readUTF();
				System.out.println("file name is:" + savePath);
				DataOutputStream fileOut = new DataOutputStream(
						new BufferedOutputStream(new BufferedOutputStream(
								new FileOutputStream(savePath))));

				long len = inStream.readLong();
				System.out.println("file length is:" + len + "\n");
				System.out.println("begin receive file!" + "\n");

				int read = 0;
				while (true) {

					if (inStream != null) {
						read = inStream.read(buf);
					}
					passedlen += read;
					if (read == -1) {
						break;
					}
					
					System.out.println("receive:" + (passedlen * 100 / len)
							+ "%\n");
					fileOut.write(buf, 0, read);
				}

				System.out.println("receive completed, and save file to" + savePath + "\n");

				fileOut.close();
			} catch (Exception e) {
				System.out.println("****receive error" + "\n");
				e.printStackTrace();
				return;
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new Client();
	}

}
